import React, { useState } from 'react';
import {
  Form,
  Input,
  Button,
  Card,
  Upload,
  Select,
  Switch,
  message,
  Row,
  Col,
  Tabs,
  Space,
} from 'antd';
import {
  UploadOutlined,
  SaveOutlined,
  ArrowLeftOutlined,
  PlusOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import type { UploadFile, UploadProps } from 'antd';

const { Option } = Select;
const { TextArea } = Input;
const { TabPane } = Tabs;

interface CardForm {
  word: string;
  phrase: string;
  pronunciation?: string;
  description?: string;
  language: string;
  topics: string[];
  status: boolean;
  image?: UploadFile[];
  audio?: UploadFile[];
}

const CardCreate: React.FC = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [imageFileList, setImageFileList] = useState<UploadFile[]>([]);
  const [audioFileList, setAudioFileList] = useState<UploadFile[]>([]);

  // 提交表单
  const onFinish = async (values: CardForm) => {
    setLoading(true);
    try {
      // 这里应该调用创建API
      console.log('Creating card with values:', values);
      console.log('Image files:', imageFileList);
      console.log('Audio files:', audioFileList);
      
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      message.success('卡片创建成功');
      navigate('/cards');
    } catch (error) {
      message.error('创建失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 图片上传配置
  const imageUploadProps: UploadProps = {
    name: 'file',
    action: '/api/admin/upload/image',
    listType: 'picture-card',
    fileList: imageFileList,
    beforeUpload: (file) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        message.error('只能上传 JPG/PNG 格式的图片!');
        return false;
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        message.error('图片大小不能超过 2MB!');
        return false;
      }
      return true;
    },
    onChange: ({ fileList }) => {
      setImageFileList(fileList);
    },
    onPreview: (file) => {
      const src = file.url || file.preview;
      if (src) {
        const image = new Image();
        image.src = src;
        const imgWindow = window.open(src);
        imgWindow?.document.write(image.outerHTML);
      }
    },
  };

  // 音频上传配置
  const audioUploadProps: UploadProps = {
    name: 'file',
    action: '/api/admin/upload/audio',
    fileList: audioFileList,
    beforeUpload: (file) => {
      const isAudio = file.type.startsWith('audio/');
      if (!isAudio) {
        message.error('只能上传音频文件!');
        return false;
      }
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        message.error('音频文件大小不能超过 5MB!');
        return false;
      }
      return true;
    },
    onChange: ({ fileList }) => {
      setAudioFileList(fileList);
    },
  };

  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>上传图片</div>
    </div>
  );

  return (
    <div>
      {/* 页面头部 */}
      <div style={{ marginBottom: 24, display: 'flex', alignItems: 'center' }}>
        <Button
          icon={<ArrowLeftOutlined />}
          onClick={() => navigate('/cards')}
          style={{ marginRight: 16 }}
        >
          返回列表
        </Button>
        <h1 style={{ margin: 0 }}>创建新卡片</h1>
      </div>

      <Card>
        <Form
          form={form}
          layout="vertical"
          onFinish={onFinish}
          initialValues={{
            language: 'en',
            status: true,
          }}
        >
          <Tabs defaultActiveKey="basic">
            {/* 基础信息 */}
            <TabPane tab="基础信息" key="basic">
              <Row gutter={[16, 16]}>
                <Col xs={24} md={12}>
                  <Form.Item
                    name="word"
                    label="单词"
                    rules={[
                      { required: true, message: '请输入单词' },
                      { min: 1, max: 50, message: '单词长度在1-50个字符之间' },
                    ]}
                  >
                    <Input placeholder="请输入单词" />
                  </Form.Item>
                </Col>
                <Col xs={24} md={12}>
                  <Form.Item
                    name="phrase"
                    label="短语/翻译"
                    rules={[
                      { required: true, message: '请输入短语或翻译' },
                      { min: 1, max: 100, message: '短语长度在1-100个字符之间' },
                    ]}
                  >
                    <Input placeholder="请输入短语或翻译" />
                  </Form.Item>
                </Col>
                <Col xs={24} md={12}>
                  <Form.Item
                    name="pronunciation"
                    label="发音"
                    rules={[
                      { max: 100, message: '发音长度不能超过100个字符' },
                    ]}
                  >
                    <Input placeholder="请输入发音（可选）" />
                  </Form.Item>
                </Col>
                <Col xs={24} md={12}>
                  <Form.Item
                    name="language"
                    label="语言"
                    rules={[{ required: true, message: '请选择语言' }]}
                  >
                    <Select placeholder="选择语言">
                      <Option value="en">英语</Option>
                      <Option value="zh">中文</Option>
                      <Option value="es">西班牙语</Option>
                      <Option value="fr">法语</Option>
                    </Select>
                  </Form.Item>
                </Col>
                <Col xs={24}>
                  <Form.Item
                    name="description"
                    label="描述"
                    rules={[
                      { max: 500, message: '描述长度不能超过500个字符' },
                    ]}
                  >
                    <TextArea
                      rows={4}
                      placeholder="请输入卡片描述（可选）"
                      showCount
                      maxLength={500}
                    />
                  </Form.Item>
                </Col>
              </Row>
            </TabPane>

            {/* 分类和状态 */}
            <TabPane tab="分类设置" key="category">
              <Row gutter={[16, 16]}>
                <Col xs={24} md={12}>
                  <Form.Item
                    name="topics"
                    label="主题分类"
                    rules={[{ required: true, message: '请选择至少一个主题' }]}
                  >
                    <Select
                      mode="multiple"
                      placeholder="选择主题分类"
                      style={{ width: '100%' }}
                    >
                      <Option value="水果">水果</Option>
                      <Option value="动物">动物</Option>
                      <Option value="颜色">颜色</Option>
                      <Option value="数字">数字</Option>
                      <Option value="形状">形状</Option>
                      <Option value="食物">食物</Option>
                      <Option value="交通工具">交通工具</Option>
                      <Option value="家庭">家庭</Option>
                    </Select>
                  </Form.Item>
                </Col>
                <Col xs={24} md={12}>
                  <Form.Item
                    name="status"
                    label="状态"
                    valuePropName="checked"
                  >
                    <Switch
                      checkedChildren="启用"
                      unCheckedChildren="禁用"
                    />
                  </Form.Item>
                </Col>
              </Row>
            </TabPane>

            {/* 媒体文件 */}
            <TabPane tab="媒体文件" key="media">
              <Row gutter={[16, 16]}>
                <Col xs={24} md={12}>
                  <Form.Item label="卡片图片">
                    <Upload {...imageUploadProps}>
                      {imageFileList.length >= 1 ? null : uploadButton}
                    </Upload>
                    <div style={{ marginTop: 8, color: '#666', fontSize: 12 }}>
                      支持 JPG、PNG 格式，文件大小不超过 2MB
                    </div>
                  </Form.Item>
                </Col>
                <Col xs={24} md={12}>
                  <Form.Item label="发音音频">
                    <Upload {...audioUploadProps}>
                      <Button icon={<UploadOutlined />}>上传音频</Button>
                    </Upload>
                    <div style={{ marginTop: 8, color: '#666', fontSize: 12 }}>
                      支持 MP3、WAV 格式，文件大小不超过 5MB
                    </div>
                  </Form.Item>
                </Col>
              </Row>
            </TabPane>
          </Tabs>

          {/* 提交按钮 */}
          <div style={{ marginTop: 24, textAlign: 'center' }}>
            <Space size="large">
              <Button size="large" onClick={() => navigate('/cards')}>
                取消
              </Button>
              <Button
                type="primary"
                size="large"
                htmlType="submit"
                loading={loading}
                icon={<SaveOutlined />}
              >
                创建卡片
              </Button>
            </Space>
          </div>
        </Form>
      </Card>
    </div>
  );
};

export default CardCreate;